package com.hqyj.realm;


import com.hqyj.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: cj
 * @Date: 2020/8/3 20:07
 * @Version: 1.0
 */
public class MyRealm extends AuthorizingRealm {
   /* @Autowired
    ServiceDao serviceDao;
    @Autowired
    RoleMapper roleMapper;*/
    /*
    * 授权
    * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //获取用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        String roleName=null;
        //User的成员int id, String account, String password, String name, String role_id, String sex, String phone
        User u =new User(1,"zs","123","张三","1","男","12813192123");
        int roleId = Integer.parseInt(u.getRole_id());
        if(roleId==1){
            roleName="经理";
        }
        System.out.println("进入授权:"+roleName);

        simpleAuthorizationInfo.addRole(roleName);
        return simpleAuthorizationInfo;
    }


    /*
    * 认证
    * */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取当前登录人的用户名(token是登录凭证)
        String userName = (String) authenticationToken.getPrincipal();
        System.out.println("这是userName的参数:"+userName);
        //通过该用户名去数据库查询
        /*User u = serviceDao.queryUserByUserName(userName);*/

        //User的成员int id, String account, String password, String name, String role_id, String sex, String phone
        User u=new User(1,userName,"123","张三","1","男","12813192123");
//        SecurityUtils.getSubject().getSession().setAttribute("userRoleId", u.getRole_id());
//        SecurityUtils.getSubject().getSession().setAttribute("userId", u.getId());
        SecurityUtils.getSubject().getSession().setAttribute("u", u);

        System.out.println("进入认证环节");
        // 返回认证信息由父类AuthenticatingRealm进行认证
        //subject.login()执行的时候调用doGetAuthenticationInfo()方法
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, u.getPassword(), getName());
        return simpleAuthenticationInfo;
    }
}
